package com.menu.web;


import com.alibaba.fastjson2.JSONObject;
import org.junit.Test;
import org.springframework.http.*;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;


public class HttpRequestTest {
    /**
     * Spring Boot Post请求
     */
    @Test
    public void testPostRequest() {
        String url = "http://47.98.173.42:8080/api/index/login";
        //        请求表
        JSONObject paramMap = new JSONObject();
        paramMap.put("userId", "admin");
        paramMap.put("password", "123456");
        //        请求头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.set("user-agent", "Mozilla/5.0 WindSnowLi-Blog");
        //        整合请求头和请求参数
        HttpEntity<JSONObject> httpEntity = new HttpEntity<>(paramMap, headers);
        //         请求客户端
        RestTemplate client = new RestTemplate();
        //      发起请求
        JSONObject body = client.postForEntity(url, httpEntity, JSONObject.class).getBody();
        System.out.println("******** POST请求 *********");
        assert body != null;
        System.out.println(body.toJSONString());
    }

    /**
     * Spring Boot Get请求
     */
    @Test
    public void testGetRequest() {
        String url = "http://47.98.173.42:8080/api/rz/get/type/list";
        HttpHeaders headers = new HttpHeaders();

        headers.add("token", "52fe8289ecf74439b39914f6419f5ed0");
        //         请求客户端
        RestTemplate client = new RestTemplate();


        //      发起请求
        String body = client.getForEntity(url, String.class, headers).getBody();
        System.out.println("******** Get请求 *********");
        assert body != null;


        HttpEntity<MultiValueMap<String, Object>> httpEntity = new HttpEntity<MultiValueMap<String, Object>>(null, headers);
        ResponseEntity<String> response2 = client.exchange(url, HttpMethod.GET, httpEntity, String.class, new HashMap<String, Object>());
        JSONObject jsonObject = JSONObject.parseObject(response2.getBody());
        List<String> data = jsonObject.getJSONArray("data").stream().map(t -> ((JSONObject) t).getString("typeName")).collect(Collectors.toList());
        List<String> collect = data.stream().filter(t -> t.contains(",")).distinct().collect(Collectors.toList());
        System.out.println(collect);
    }
}

